/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.emergency.bean.MaterialHiddenDanger;
import com.koron.emergency.domain.EmergencyMaterial;
import com.koron.emergency.domain.MaterialCheckRecord;
import com.koron.emergency.domain.MaterialCheckRelation;
import com.koron.emergency.mapper.EmergencyDeviceMapper;
import com.koron.emergency.mapper.EmergencyMaterialMapper;
import com.koron.emergency.mapper.MaterialCheckRecordMapper;
import com.koron.emergency.service.api.MaterialCheckRecordService;
import com.koron.emergency.util.BusinessCode;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.service.api.IndicationItemsService;
import com.koron.hazardsource.util.Immutable;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.mapper.CheckMapper;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.hiddendanger.service.impl.HiddenDangerDiscoveryServiceImpl;
import com.koron.hiddendanger.service.impl.HiddenDangerRectificationServiceImpl;
import com.koron.risk.service.api.GridNodeService;
import com.koron.risk.util.GridHelpUtils;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import com.koron.system.domain.DictData;
import com.koron.system.domain.Message;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.mapper.MessageMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.google.gson.internal.bind.util.ISO8601Utils.format;

@Service
public class MaterialCheckRecordServiceImpl implements MaterialCheckRecordService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(MaterialCheckRecordServiceImpl.class);

    @Autowired
    private HiddenDangerDiscoveryService dangerDiscoveryService;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private HiddenDangerDiscoveryService discoveryService;


    @Autowired
    private IndicationItemsService indicationItemsService;


    @Autowired
    private Util util;

    @Value("${materialcheck_confirm}")
    private String flowTemplate;

    @Value("${contingency_manage_setCode}")
    private String contingencyManageSetCode;

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    @Value("${danger_work_flow}")
    private String hiddenDangerWorkFlow;

    @Override
    public MessageBean<String> save(MaterialCheckRecord checkRecord) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", String.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(checkRecord.getTitle())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_TITLE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_TITLE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(checkRecord.getCorpCode())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CORPCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(checkRecord.getCheckEmployeeCode()) || StringUtils.isEmpty(checkRecord.getCheckEmployeeName())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHECKEMPLOYEECODE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHECKEMPLOYEECODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(checkRecord.getExecuterCode()) || StringUtils.isEmpty(checkRecord.getExecuterName())) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_EXCUTORCODES.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_EXCUTORCODES.getDescription());
                return msg;
            }
            if (null == checkRecord.getCheckTime()) {
                msg.setCode(BusinessCode.CHECKRECORD_EMPTY_CHECKTIME.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_EMPTY_CHECKTIME.getDescription());
                return msg;
            }
            Integer count = factory.getMapper(MaterialCheckRecordMapper.class).doubleTitle(checkRecord.getTitle(), checkRecord.getId());
            if (count > 0) {
                msg.setCode(BusinessCode.CHECKRECORD_DOUBLE_TITLE.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_DOUBLE_TITLE.getDescription());
                return msg;
            }
            Integer value = 0;
            if (StringUtils.isEmpty(checkRecord.getId())) {
                //新增
                checkRecord.setAddTime(checkRecord.getUpdateTime());
                checkRecord.setAddUser(checkRecord.getUpdateUser());
                checkRecord.setAddUserName(checkRecord.getUpdateUserName());
                checkRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                checkRecord.setStatus(1);
                value = factory.getMapper(MaterialCheckRecordMapper.class).insert(checkRecord);
            } else {
                MaterialCheckRecord entity = queryOne(checkRecord.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                    return msg;
                }
                if (entity.getStatus() == 2) {
                    msg.setCode(BusinessCode.CHECKRECORD_IS_COMFIRMED.getCode());
                    msg.setDescription(BusinessCode.CHECKRECORD_IS_COMFIRMED.getDescription());
                    return msg;
                }
                value = factory.getMapper(MaterialCheckRecordMapper.class).update(checkRecord);
            }
            if (value > 0) {
                msg.setData(checkRecord.getId());
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            if (1 != entity.getStatus()) {
                msg.setCode(BusinessCode.CHECKRECORD_IS_COMFIRMED.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_IS_COMFIRMED.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(MaterialCheckRecordMapper.class).delete(id);
            if (value < 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
            }
            msg.setData(value);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<MaterialCheckRecord> queryOne(String id) {
        MessageBean<MaterialCheckRecord> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询检查记录详情成功", MaterialCheckRecord.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord entity = factory.getMapper(MaterialCheckRecordMapper.class).queryOne(id);
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<MaterialCheckRecord>> queryByCondition(String corpCode, String title, String checkEmployeeName, String executerName, Integer status, Integer start, Integer rows, String keyword) {
        MessageBean<DataBean<MaterialCheckRecord>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<MaterialCheckRecord> list = factory.getMapper(MaterialCheckRecordMapper.class).queryByCondition(corpCode, title, checkEmployeeName, executerName, status, start, rows,keyword);
            Integer totalNumber = factory.getMapper(MaterialCheckRecordMapper.class).countByCondition(corpCode, title, checkEmployeeName, executerName, status,keyword);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1 : 1;
            DataBean<MaterialCheckRecord> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取检查记录列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> saveCheckAttachment(String id, MultipartFile[] files, String keepfiles, String delFiles) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "上传成功", Integer.class);
        List<String> keepList = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                }
            }
            if (StringUtils.isNotEmpty(keepfiles)) {
                String[] keepArray = keepfiles.split("[,，;；]");
                keepList.addAll(Arrays.asList(keepArray));
            }

            Integer value = factory.getMapper(MaterialCheckRecordMapper.class).updateCheckAttachment(new Gson().toJson(keepList), id);
            if (value < 0) {
                if (null != keepList && keepList.size() > 0) {
                    if (StringUtils.isEmpty(keepfiles)) {
                        for (String url : keepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(keepfiles.split("[,，]"));
                        for (String url : keepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("上传失败");
            } else {
                if (StringUtils.isNotEmpty(delFiles)) {
                    String[] delArray = delFiles.split("[,，]");
                    for (String delUrl : delArray) {
                        clientWrapper.deleteFile(delUrl.split("#")[0]);
                    }
                }
            }
            msg.setData(value);
            return msg;
        } catch (Exception e) {
            if (null != keepList && keepList.size() > 0) {
                if (StringUtils.isEmpty(keepfiles)) {
                    for (String url : keepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepfiles.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> fileList(String id) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询附件列表成功", List.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            List<Map> list = new ArrayList<Map>();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取附件列表成功");
            if (StringUtils.isNotEmpty(entity.getAttachment())) {
                List<String> orginList = JSONObject.parseArray(entity.getAttachment(), String.class);
                if (null != orginList && orginList.size() > 0) {
                    for (String url : orginList) {
                        Map<String, String> map = new HashMap<>();
                        map.put("id", id);
                        map.put("fileName", url.split("#")[1]);
                        map.put("fileAddress", url);
                        list.add(map);
                    }
                }
            }
            msg.setData(list);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<EmergencyMaterial>> queryCheckDeatils(String corpCode, String checkRecordId, String checkEmployeeCode, Integer start, Integer rows) {
        MessageBean<DataBean<EmergencyMaterial>> msg = new MessageBean<>();
        List<EmergencyMaterial> list = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(checkRecordId) || StringUtils.isEmpty(checkEmployeeCode)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord record = queryOne(checkRecordId).getData();
            if (null == record) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            list = factory.getMapper(EmergencyMaterialMapper.class).queryByCheckManagerCode(corpCode, checkEmployeeCode);
            for (EmergencyMaterial material : list) {
                material.setNormal(null);
                material.setHiddenDangers(null);
            }
            Integer totalNumber = list.size();
            List<MaterialCheckRelation> relations = factory.getMapper(MaterialCheckRecordMapper.class).queryRelationByCondition(checkRecordId, null, null, null);
            if (null != relations && relations.size() > 0) {
                for (MaterialCheckRelation relation : relations) {
                    list.stream().forEach(m -> {
                        if (m.getId().equals(relation.getMaterialId())) {
                            m.setNormal(relation.getNormal());
                            if (StringUtils.isNotEmpty(relation.getHiddenDangerIds())) {
                                //根据这些id去查询这些隐患
                                List<String> idList = JSONObject.parseArray(relation.getHiddenDangerIds(), String.class);
                                if (null != idList && idList.size() > 0) {
                                    List<HiddenDangerDiscovery> dangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(idList);
                                    if (null != dangerDiscoveries && dangerDiscoveries.size() > 0) {
                                        dangerDiscoveries.forEach(item -> dangerDiscoveryService.getNames(item));
                                        m.setHiddenDangers(dangerDiscoveries);
                                    }
                                }
                            }
                        }
                    });
                }
            }
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            Integer end = (start == 0 ? 1 : start) * rows;
            if (end > list.size()) {
                end = list.size();
                if (start > end) {
                    start = end;
                }
            }
            DataBean<EmergencyMaterial> dataBean = new DataBean<>();
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            dataBean.setList(list.subList(start, end));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取应急物资检查记录明细列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> saveRealtion(StaffBean user, MaterialCheckRelation relation) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        SessionFactory factory = new SessionFactory();
        try {
            if (null == relation) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            List<MaterialHiddenDanger> dangerList = relation.getMaterialHiddenDangerList();
            if (null != dangerList && dangerList.size() > 0) {
                boolean flag = true;
                HiddenDangerMapper dangerMapper = factory.getMapper(HiddenDangerMapper.class);
                for (MaterialHiddenDanger danger : dangerList) {
                    if (StringUtils.isNotEmpty(danger.getId())) {
                        //修改的隐患
                        HiddenDangerDiscovery entity = dangerMapper.queryDangerOne(danger.getId());
                        if (null == entity && entity.getState() != 0 && entity.getState() != 7) {
                            factory.close(false);
                            msg.setCode(BusinessCode.HIDDENDANGER_CANNOT_EDIT.getCode());
                            msg.setDescription(BusinessCode.HIDDENDANGER_CANNOT_EDIT.getDescription());
                            return msg;
                        }
                    }
                    List<String> newAtts = new ArrayList<>();
                    List<MultipartFile> files = danger.getFiles();
                    if (null != files && !files.isEmpty()) {
                        for (MultipartFile file : files) {
                            String url = clientWrapper.uploadFile(file);
                            newAtts.add(url + "#" + file.getOriginalFilename());
                        }
                    }
                    try {
                        flag = process(factory, user, danger, newAtts, relation.getMaterialCheckRecordId());
                        //attachmentList.addAll(newAtts);
                    } catch (Exception e) {
                        flag = false;
                        logger.error(e.getMessage(),e);
                    }
                    if (!flag) {
                        //处理隐患失败即退出循环
                        break;
                    }
                }
                if (!flag) {
                    // removeAttachment(attachmentList);
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                    return msg;
                }
                List<String> collect = dangerList.stream().map(MaterialHiddenDanger::getId).collect(Collectors.toList());
                relation.setHiddenDangerIds(new Gson().toJson(collect));
            }
            MaterialCheckRecordMapper recordMapper = factory.getMapper(MaterialCheckRecordMapper.class);
            MaterialCheckRelation entity = recordMapper.queryOneRelation(relation.getMaterialCheckRecordId(), relation.getMaterialId());
            if (null == entity) {
                //新增
                recordMapper.insertRelation(relation);
                factory.close();
                return msg;
            } else {
                //修改
                if (StringUtils.isNotEmpty(entity.getHiddenDangerIds())) {
                    if (StringUtils.isNotEmpty(relation.getHiddenDangerIds()) && !StringUtils.equals(entity.getHiddenDangerIds(), relation.getHiddenDangerIds())) {
                        List<String> orginList = JSONObject.parseArray(entity.getHiddenDangerIds(), String.class);
                        List<String> targetList = JSONObject.parseArray(relation.getHiddenDangerIds(), String.class);
                        List<String> delIdList = new ArrayList<>();
                        for (String id : orginList) {
                            if (!targetList.contains(id))
                                delIdList.add(id);
                        }
                        if (null != delIdList && delIdList.size() > 0) {
                            factory.getMapper(HiddenDangerMapper.class).batchDeleteDanger(delIdList);
                        }
                    }
                }
                recordMapper.updateRelation(relation);
                factory.close();
                return msg;
            }
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    private boolean process(SessionFactory factory, StaffBean user, MaterialHiddenDanger danger, List<String> newAtts, String materialCheckRecordId) throws Exception {
        danger.setCheckRecordId(materialCheckRecordId);
        danger.setUpdateUser(user.getName());
        danger.setUpdateTime(new Date());
        danger.setSubmitterCode(user.getCode() + "_" + user.getUserid());
        danger.setDerivation(5);
        MessageBean<?> corpMsg = util.corp(user.getCode());
        if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
            DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
            danger.setCheckUnit(corp.getDepartmentCode());
            danger.setCheckUnitName(corp.getName());
        }
        if (StringUtils.isNotEmpty(danger.getInnerStaff())) {
            String[] arrays = danger.getInnerStaff().split("[,，]");
            danger.setInnerStaff(new Gson().toJson(Arrays.asList(arrays)));
        }
        if (StringUtils.isNotEmpty(danger.getDiscovererCode())) {
            String[] arrays = danger.getDiscovererCode().split("[,，]");
            danger.setDiscovererCode(new Gson().toJson(Arrays.asList(arrays)));
        }
        if (StringUtils.isNotEmpty(danger.getDiscovererDepartment())) {
            String[] arrays = danger.getDiscovererDepartment().split("[,，]");
            danger.setDiscovererDepartment(new Gson().toJson(Arrays.asList(arrays)));
        }
        //草稿
        danger.setState(7);
        IndicationItems itemsUnfinish = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
        if (StringUtils.isEmpty(danger.getId())) {
            danger.setId(DefaultIdGenerator.getInstance().generateLongId());
            danger.setCode(dangerDiscoveryService.generateCode(factory, danger));
            danger.setAddTime(danger.getUpdateTime());
            danger.setAddUser(danger.getUpdateUser());
            Port port = dangerDiscoveryService.getPort();
            List<DeptBean> departmentTreeBeanList = port.dept(user == null ? "1c6646fffe514a4c9539ba05fd3d92eb" : user.getCode()).getData();
            danger.setSubmitterDepartment(departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0 ? null : departmentTreeBeanList.get(0).getCode());
            if (null != newAtts && newAtts.size() > 0) {
                danger.setAttachment(new Gson().toJson(newAtts));
            }
            if (StringUtils.isEmpty(danger.getDeviceCode())) {
                danger.setDeviceCode("LSHDD" + danger.getId().substring(danger.getId().length() - 8));
            }
            factory.getMapper(HiddenDangerMapper.class).insertDanger(danger);
            //构建隐患整改记录，填充整改人、整改期限、验证人、确认人、整改措施等信息
            HiddenDangerRectification rectification = new HiddenDangerRectification();
            rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
            rectification.setConfirmPerson(danger.getConfirmPerson());
            rectification.setConfirmPersonName(danger.getConfirmPersonName());
            rectification.setRectifier(danger.getDangerManager());
            rectification.setRectifierName(danger.getDangerManagerName());
            rectification.setReviewer(danger.getDangerManager().split("_")[0]);
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(danger.getDangerManager().split("_")[0], null).getData();
            List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(danger.getDangerManager().split("_")[0]).getData();
            rectification.setReviewerName(null != staffBeanList && null != deptBeanList ? staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName() : danger.getReviewerName());
            rectification.setUpdateUser(danger.getUpdateUser());
            rectification.setUpdateUserName(danger.getUpdateUserName());
            rectification.setAddUser(danger.getAddUser());
            rectification.setAddUserName(danger.getAddUserName());
            rectification.setAddTime(danger.getAddTime());
            rectification.setUpdateTime(danger.getUpdateTime());
            rectification.setDeadline(danger.getDeadline());
            rectification.setSolution(danger.getSolution());
            rectification.setHiddenDangerId(danger.getId());
            rectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
            rectification.setDelayState(0);
            factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
            return true;
        } else {
            if (StringUtils.isEmpty(danger.getDeviceCode())) {
                danger.setDeviceCode("LSHDD" + danger.getId().substring(danger.getId().length() - 8));
            }
            List<String> keepAttsList = new ArrayList<>();
            keepAttsList.addAll(newAtts);
            if (StringUtils.isNotEmpty(danger.getKeepAtts())) {
                String[] keepAttsArray = danger.getKeepAtts().split("[;；]");
                keepAttsList.addAll(Arrays.asList(keepAttsArray));
            }
            if (keepAttsList.size() > 0) {
                danger.setAttachment(new Gson().toJson(keepAttsList));
            }
            if (factory.getMapper(HiddenDangerMapper.class).updateDanger(danger) > 0) {
                if (StringUtils.isNotEmpty(danger.getDelAtts())) {
                    String[] delAttsArray = danger.getDelAtts().split("[;；]");
                    for (String att : delAttsArray) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
                //判断是否填写了隐患整改信息
                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(danger.getId());
                HiddenDangerRectification rectification = new HiddenDangerRectification();
                rectification.setConfirmPerson(danger.getConfirmPerson());
                rectification.setConfirmPersonName(danger.getConfirmPersonName());
                rectification.setRectifier(danger.getDangerManager());
                rectification.setRectifierName(danger.getDangerManagerName());
                rectification.setReviewer(danger.getDangerManager().split("_")[0]);
                List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(danger.getDangerManager().split("_")[0], null).getData();
                List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(danger.getDangerManager().split("_")[0]).getData();
                rectification.setReviewerName(null != staffBeanList && null != deptBeanList ? staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName() : danger.getReviewerName());
                rectification.setUpdateUser(danger.getUpdateUser());
                rectification.setUpdateUserName(danger.getUpdateUserName());
                rectification.setAddUser(danger.getAddUser());
                rectification.setAddUserName(danger.getAddUserName());
                rectification.setAddTime(danger.getAddTime());
                rectification.setUpdateTime(danger.getUpdateTime());
                rectification.setDeadline(danger.getDeadline());
                rectification.setSolution(danger.getSolution());
                rectification.setHiddenDangerId(danger.getId());
                rectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
                rectification.setDelayState(0);
                if (null == rectificationList || rectificationList.size() <= 0) {
                    rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                    factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
                    return true;
                } else {
                    rectification.setId(rectificationList.get(0).getId());
                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                    return true;
                }
            }
            return false;
        }
    }

    @Override
    public MessageBean<?> viewReport(String checkRecordId) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "预览成功", Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.isEmpty(checkRecordId)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord entity = queryOne(checkRecordId).getData();
            if (null != entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            StringBuilder name = new StringBuilder("检查负责人：");
            name.append(entity.getCheckEmployeeName());
            if (StringUtils.isNotEmpty(entity.getExecuterName())) {
                name.append("检查执行人");
                List<String> names = JSONObject.parseArray(entity.getExecuterName(), String.class);
                for (String na : names) {
                    name.append(na).append(",");
                }
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            map.put("title", entity.getTitle());
            map.put("checkDeptName", entity.getCheckDeptName());
            map.put("checkName", name.toString());
            map.put("checkTime", format(entity.getCheckTime()));
            map.put("description", entity.getDescription());
            List<EmergencyMaterial> materialList = queryCheckDeatils(entity.getCorpCode(), checkRecordId, entity.getCheckEmployeeCode(), null, null).getData().getList();
            map.put("materialList", materialList);
            List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(checkRecordId, null, null);
            map.put("dangerDiscoveryList", dangerDiscoveryList);
            msg.setData(map);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> commit(StaffBean user, String checkRecordId, String jobTaskId) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "提交成功", Integer.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            MaterialCheckRecordMapper recordMapper = factory.getMapper(MaterialCheckRecordMapper.class);
            HiddenDangerMapper dangerMapper = factory.getMapper(HiddenDangerMapper.class);
            if (StringUtils.isEmpty(checkRecordId)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord entity = queryOne(checkRecordId).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(checkRecordId, null, null);
            entity.setStatus(2);
            recordMapper.update(entity);

            if (StringUtils.isNotEmpty(jobTaskId)) {
                //更新任务
                JobsTasks jobsTasks = factory.getMapper(JobsTasksMapper.class).queryById(jobTaskId);
                if (null != jobsTasks) {
                    jobsTasks.setBusinessId(checkRecordId);
                    jobsTasks.setState(3);
                    jobsTasks.setCompletedTime(new Date());
                    factory.getMapper(JobsTasksMapper.class).completed(jobsTasks);
                }
            }
            //将检查过程中发现的隐患状态设置为6：处于检查会签中的隐患，无法编辑，无法提交，
            //检查流程审批通过之后设置为草稿状态，这时可以提交隐患流程
            if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveryList) {
                    dangerDiscovery.setState(6);
                }
                dangerMapper.batchUpdateDanger(dangerDiscoveryList);
            }
            //构造Audit
            Date date = new Date();
            Audit audit = new Audit();
            audit.setAddUser(user == null ? null : user.getName());
            audit.setAddTime(date);
            audit.setUpdateUser(user == null ? null : user.getName());
            audit.setUpdateTime(date);
            audit.setFlowType(1);
            audit.setFlowName(Immutable.MATERIAL_RESULT_CONFIRM);
            audit.setOperation(1);
            audit.setTarget(MaterialCheckRecordServiceImpl.class.getName());
            audit.setTitle(entity.getTitle());
            audit.setCorpCode(entity.getCorpCode());
            audit.setBusinessIds(entity.getId());
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("应急物资检查记录描述为：" + entity.getDescription());
            audit.setState(1);
            audit.setTemplateKey(flowTemplate);
            audit.setInitiatorAccount(user.getUserid());
            audit.setSetCode(contingencyManageSetCode);
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            Map<String, Object> businessMap = new HashMap<>();
            businessMap.put("manager", entity.getCheckEmployeeCode().split("_")[1]);
            if (StringUtils.isNotEmpty(entity.getExecuterCode())) {
                List<String> excuterCodes = JSONObject.parseArray(entity.getExecuterCode(), String.class);
                StringBuilder codes = new StringBuilder();
                for (String code : excuterCodes) {
                    codes.append(code.split("_")[1]).append(",");
                }
                businessMap.put("executors", codes.toString().substring(0, codes.lastIndexOf(",")));
            }
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交失败，原因是无法启动流程");
                return msg;
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<MaterialCheckRelation> queryRelationDeatils(String materialId, String materialCheckId) {
        MessageBean<MaterialCheckRelation> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), MaterialCheckRelation.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(materialId) || StringUtils.isEmpty(materialCheckId)) {
                msg.setCode(BusinessCode.EMPTY_PARAM.getCode());
                msg.setDescription(BusinessCode.EMPTY_PARAM.getDescription());
                return msg;
            }
            MaterialCheckRelation relation = factory.getMapper(MaterialCheckRecordMapper.class).queryOneRelation(materialCheckId, materialId);
            msg.setData(relation);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<MaterialCheckRecord> exportList(StaffBean user, String corpCode, String title, String checkEmployeeName, String executerName, Integer status) {
        try (SessionFactory factory = new SessionFactory()) {
            List<MaterialCheckRecord> list = factory.getMapper(MaterialCheckRecordMapper.class).queryByCondition(corpCode, title, checkEmployeeName, executerName, status, null, null,null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                list.forEach(bean -> {
                    if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                    if (null != bean.getCheckTime()) {
                        bean.setCheckTimeStr(sdf.format(bean.getCheckTime()));
                    }
                    if (StringUtils.isNotEmpty(bean.getExecuterName())) {
                        bean.setExecuterName(JSONObject.parseArray(bean.getExecuterName(), String.class).stream().collect(Collectors.joining(",")));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<EmergencyMaterial> queryOneCheckDeatils(String corpCode, String checkRecordId, String checkEmployeeCode, String emergencyMaterialId) {
        MessageBean<EmergencyMaterial> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(checkRecordId) || StringUtils.isEmpty(checkEmployeeCode)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            MaterialCheckRecord record = queryOne(checkRecordId).getData();
            if (null == record) {
                msg.setCode(BusinessCode.CHECKRECORD_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CHECKRECORD_NOT_EXIST.getDescription());
                return msg;
            }
            EmergencyMaterial material = factory.getMapper(EmergencyMaterialMapper.class).queryOneByCheckManagerCode(corpCode, checkEmployeeCode, emergencyMaterialId);
            if (null != material) {
                String materialType = material.getMaterialType();
                if (StringUtils.isNotEmpty(materialType)) {
                    DictData dictData = factory.getMapper(DictDataMapper.class).queryOne(materialType);
                    if (dictData != null) {
                        material.setMaterialTypeName(dictData.getDictLabel());
                    }
                }
                material.setNormal(null);
                material.setHiddenDangers(null);
                List<MaterialCheckRelation> relations = factory.getMapper(MaterialCheckRecordMapper.class).queryRelationByCondition(checkRecordId, null, null, null);
                if (null != relations && relations.size() > 0) {
                    for (MaterialCheckRelation relation : relations) {
                        if (material.getId().equals(relation.getMaterialId())) {
                            material.setNormal(relation.getNormal());
                            if (StringUtils.isNotEmpty(relation.getHiddenDangerIds())) {
                                //根据这些id去查询这些隐患
                                List<String> idList = JSONObject.parseArray(relation.getHiddenDangerIds(), String.class);
                                if (null != idList && idList.size() > 0) {
                                    List<HiddenDangerDiscovery> dangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(idList);
                                    if (null != dangerDiscoveries && dangerDiscoveries.size() > 0) {
                                        dangerDiscoveries.forEach(item -> dangerDiscoveryService.getNames(item));
                                        material.setHiddenDangers(dangerDiscoveries);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取应急物资检查记录单条明细成功");
            msg.setData(material);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }

    }

    @Override
    public MessageBean<?> saveCheckDanger(StaffBean user, String materialCheckRecordId, String materialId, HiddenDangerDiscovery dangerDiscovery, String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        MessageBean<?> msg = new MessageBean<>();
        List<String> newAtts = new ArrayList<>();
        SessionFactory factory = null;
        try {
            MaterialCheckRelation relation=new MaterialCheckRelation();
            if (StringUtils.isEmpty(materialId)) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("物资id不能为空");
                return msg;
            }
            relation.setMaterialId(materialId);
            if (StringUtils.isEmpty(materialCheckRecordId) && StringUtils.isEmpty(dangerDiscovery.getCheckRecordId())) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("物资检查记录id不能为空");
                return msg;
            }
            materialCheckRecordId = StringUtils.isEmpty(materialCheckRecordId) ? dangerDiscovery.getCheckRecordId() : materialCheckRecordId;
            relation.setMaterialCheckRecordId(materialCheckRecordId);
            factory = new SessionFactory();
            if (null != dangerDiscovery) {
                dangerDiscovery.setCheckRecordId(materialCheckRecordId);
                dangerDiscovery.setUpdateUser(user.getName());
                dangerDiscovery.setUpdateTime(new Date());
                dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
                if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
                    String[] arrays = dangerDiscovery.getInnerStaff().split("[,，]");
                    List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
                    dangerDiscovery.setInnerStaff(new Gson().toJson(collect));
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererCode())) {
                    String[] arrays = dangerDiscovery.getDiscovererCode().split("[,，]");
                    List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
                    dangerDiscovery.setDiscovererCode(new Gson().toJson(collect));
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererDepartment())) {
                    String[] arrays = dangerDiscovery.getDiscovererDepartment().split("[,，]");
                    List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
                    dangerDiscovery.setDiscovererDepartment(new Gson().toJson(collect));
                }
                if (StringUtils.isEmpty(dangerDiscovery.getCorpCode())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_CORPCODE.getCode());
                    msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_CORPCODE.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getGridCode())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_GRIDCODE.getCode());
                    msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_GRIDCODE.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDescription())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getElementFristType())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("一级分类不能为空");
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getElementSecondType())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("二级分类不能为空");
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDangerType())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("排序不能为空");
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDangerLevel())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("隐患分级不能为空");
                    return msg;
                }
                if (null != files && files.length > 0) {
                    for (MultipartFile file : files) {
                        String fileName = file.getOriginalFilename();
                        //获取文件后缀名
                        String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        //判断是否属于图片
                        boolean contains = Lists.newArrayList("bmp", "gif", "jpg", "psd", "tiff", "eps", "tga", "jpeg", "png").contains(substring);
                        if (!contains) {
                            msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.FAILURE.getCode());
                            msg.setDescription(fileName + "不是图片，请上传图片");
                            return msg;
                        }
                        String url = clientWrapper.uploadFile(file);
                        newAtts.add(url + "#" + file.getOriginalFilename());
                    }
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getCheckRecordId())) {
                    Map deviceCheck = factory.getMapper(CheckMapper.class).queryDeviceCheck(dangerDiscovery.getCheckRecordId());
                    if (null != deviceCheck && !deviceCheck.isEmpty() && "1".equals(deviceCheck.get("status").toString())) {
                        dangerDiscovery.setState(7);
                    } else {
                        dangerDiscovery.setState(0);
                    }
                }
                if (StringUtils.isEmpty(dangerDiscovery.getId())) {
                    // 新增
                    dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
                    dangerDiscovery.setCode(generateCode(factory, dangerDiscovery));
                    dangerDiscovery.setAddTime(dangerDiscovery.getUpdateTime());
                    dangerDiscovery.setAddUser(dangerDiscovery.getUpdateUser());
                    if (StringUtils.isBlank(dangerDiscovery.getCheckRecordId()) && StringUtils.isBlank(dangerDiscovery.getFreeSnapId())) {
                        dangerDiscovery.setDerivation(5);
                    }
                    MessageBean<?> corpMsg = util.corp(user.getCode());
                    if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                        DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                        dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                        dangerDiscovery.setCheckUnitName(corp.getName());
                    }
                    if (null != newAtts && newAtts.size() > 0) {
                        dangerDiscovery.setAttachment(new Gson().toJson(newAtts));
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getDeviceCode())) {
                        dangerDiscovery.setDeviceCode("LSHDD-" + dangerDiscovery.getId().substring(dangerDiscovery.getId().length() - 6));
                    }
                    List<DeptBean> departmentTreeBeanList = (List<DeptBean>) util.dept(user.getCode()).getData();
                    dangerDiscovery.setSubmitterDepartment(departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0 ? null : departmentTreeBeanList.get(0).getCode());
                    factory.getMapper(HiddenDangerMapper.class).insertDanger(dangerDiscovery);
                } else {
                    //修改
                    //先判断是否已经提交过了
                    HiddenDangerDiscovery entity = factory.getMapper(HiddenDangerMapper.class).queryDangerOne(dangerDiscovery.getId());
                    if (null == entity) {
                        msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_NOT_EXISIT.getCode());
                        msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_NOT_EXISIT.getDescription());
                        return msg;
                    }
                    if (entity.getState() != 0 && entity.getState() != 7) {
                        msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_IS_COMMITED.getCode());
                        msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_IS_COMMITED.getDescription());
                        return msg;
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getCheckUnit()) && StringUtils.isEmpty(dangerDiscovery.getCheckUnitName())) {
                        if (StringUtils.isEmpty(entity.getCheckUnit()) && StringUtils.isEmpty(entity.getCheckUnitName())) {
                            MessageBean<?> corpMsg = util.corp(user.getCode());
                            if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                                DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                                dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                                dangerDiscovery.setCheckUnitName(corp.getName());
                            }
                        } else {
                            dangerDiscovery.setCheckUnit(entity.getCheckUnit());
                            dangerDiscovery.setCheckUnitName(entity.getCheckUnitName());
                        }
                    }
                    List<String> keepAttsList = new ArrayList<>();
                    if (null != newAtts && newAtts.size() > 0) {
                        keepAttsList.addAll(newAtts);
                    }
                    if (StringUtils.isNotEmpty(keepFileAddress)) {
                        String[] keepArray = keepFileAddress.split("[;；]");
                        newAtts.addAll(Arrays.asList(keepArray));
                    }
                    if (null != keepAttsList && keepAttsList.size() > 0) {
                        dangerDiscovery.setAttachment(new Gson().toJson(keepAttsList));
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getDeviceCode())) {
                        dangerDiscovery.setDeviceCode("LSHDD-" + dangerDiscovery.getId().substring(dangerDiscovery.getId().length() - 8));
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getLegalBasis()) || ("null").equals(dangerDiscovery.getLegalBasis())) {
                        dangerDiscovery.setLegalBasis("");
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getLocation()) || ("null").equals(dangerDiscovery.getLocation())) {
                        dangerDiscovery.setLocation("");
                    }
                    Integer value = factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery);
                    if (value > 0) {
                        if (StringUtils.isNotEmpty(delFileAddress)) {
                            String[] delAttsArray = delFileAddress.split("[，,]");
                            for (String att : delAttsArray) {
                                clientWrapper.deleteFile(att.split("#")[0]);
                            }
                        }
                    }
                }
            }
            MaterialCheckRecordMapper recordMapper = factory.getMapper(MaterialCheckRecordMapper.class);
            MaterialCheckRelation entity = recordMapper.queryOneRelation(relation.getMaterialCheckRecordId(), relation.getMaterialId());
            if (entity == null) {
                relation.setNormal(false);
                List<String> collect = Arrays.asList(dangerDiscovery.getId());
                relation.setHiddenDangerIds(new Gson().toJson(collect));
                recordMapper.insertRelation(relation);
                factory.close();
                return msg;
            } else {
                // 根据检查记录id查找检查记录历史信息
                String hiddenDangerIds = entity.getHiddenDangerIds();
                List<String> list = JSONObject.parseArray(hiddenDangerIds, String.class);
                if(null == list){
                    list = new ArrayList<>();
                }
                list.add(dangerDiscovery.getId());
                entity.setHiddenDangerIds(new Gson().toJson(list));
                recordMapper.updateRelation(entity);
                factory.close();
                return msg;
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), BusinessCode.FAILURE.getDescription(), void.class);
        }finally {
            if (null != factory){
                factory.close();
            }
        }

    }

    @Autowired
    private HiddenDangerDiscoveryService hiddenDangerService;

    @Override
    public MessageBean<DataBean<HiddenDangerDiscovery>> queryOneDeviceOfDanger(String corpCode, String materialId, String materialCheckRecordId, Integer page, Integer pageSize) {
        MessageBean<DataBean<HiddenDangerDiscovery>> msg = new MessageBean<>();
        DataBean dataBean = new DataBean();
        List<HiddenDangerDiscovery> deviceDangers = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            MaterialCheckRecord materialCheck = factory.getMapper(MaterialCheckRecordMapper.class).queryOne(materialCheckRecordId);
            if (null != materialCheck) {
                // 获取设备检查记录
                MaterialCheckRelation materialCheckRelation = factory.getMapper(MaterialCheckRecordMapper.class).queryOneRelation(materialCheckRecordId, materialId);
                if (null != materialCheckRelation) {
                    String hiddenDangerIds = materialCheckRelation.getHiddenDangerIds();
                    List<String> list = JSONObject.parseArray(hiddenDangerIds, String.class);
                    if (null != list && list.size() > 0) {
                        deviceDangers = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(list);
                        if (deviceDangers != null && !deviceDangers.isEmpty()) {
                            deviceDangers.forEach(item -> hiddenDangerService.getNames(item));
                        }
                    }
                }
            }
        }
        Integer total = deviceDangers.size();
        dataBean.setTotalNumber(total);
        dataBean.setPageNo(page);
        dataBean.setPageSize(pageSize);
        dataBean.setTotalPage(total > pageSize ? (total % pageSize == 0 ? total / pageSize : total / pageSize + 1) : 1);
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
                start = (page <= 1) ? 0 : (page - 1) * pageSize;
                end = page * pageSize;
            }
            if (start != null && end != null) { //需要分页
                if (end > total) {
                    end = total;
                    if (start > end) {
                        start = end;
                    }
                }
            }
        }
        dataBean.setList(deviceDangers.subList(start, end));
        msg.setData(dataBean);
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;

    }


    public String generateCode(SessionFactory factory, HiddenDangerDiscovery dangerDiscovery) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
        Integer counter = factory.getMapper(HiddenDangerMapper.class).countCode(date.substring(2, 4));
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(4); // 设置最大整数位数
        nf.setMinimumIntegerDigits(4); // 设置最小整数位数
        StringBuilder sb = new StringBuilder();
        sb.append("YD").append(date.substring(2, 4)).append(nf.format(counter));
        return sb.toString();
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            MaterialCheckRecord entity = queryOne(audit.getBusinessIds()).getData();
            if (null != entity) {
                //根据应急物资的检查记录id去查找是否有任务的存在
                JobsTasks jobsTasks = factory.getMapper(JobsTasksMapper.class).queryJobsTasksByBusinId(entity.getId());
                if (null != jobsTasks) {
                    jobsTasks.setState(1);
                    factory.getMapper(JobsTasksMapper.class).completed(jobsTasks);
                }
                //更新应急物资检查记录的状态
                entity.setStatus(3);
                MaterialCheckRecordMapper materialCheckRecordMapper = factory.getMapper(MaterialCheckRecordMapper.class);
                materialCheckRecordMapper.update(entity);

                // 更新应急设备、物资台账的最新检查日期;
                List<MaterialCheckRelation> materialCheckRelationList = materialCheckRecordMapper.queryRelationByCondition(entity.getId(), null, null, null);
                List<String> materialIdList = materialCheckRelationList.stream().map(MaterialCheckRelation::getMaterialId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(materialIdList)) {
                    EmergencyDeviceMapper emergencyDeviceMapper = factory.getMapper(EmergencyDeviceMapper.class);
                    emergencyDeviceMapper.batchUpdateLastCheckDate(materialIdList, entity.getCheckTime());
                    EmergencyMaterialMapper emergencyMaterialMapper = factory.getMapper(EmergencyMaterialMapper.class);
                    emergencyMaterialMapper.batchUpdateLastCheckDate(materialIdList, entity.getCheckTime());
                }
                // 获取检查负责人
                String manager = entity.getCheckEmployeeCode();
                IndicationItems items = indicationItemsService.matchItems("隐患整改状态", "未整改");
                StaffBean user = (StaffBean) discoveryService.getPort().staff(manager.split("_")[0], null).getData().get(0);
                //审批通过，将检查记录中的隐患启动相应的流程
                List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(audit.getBusinessIds(),
                        null, null);
                // 检查记录审批完成后，自动启动隐患整改流程
                if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                    // 获取隐患负责人
                    Set<String> codeLists = dangerDiscoveryList.stream().map(bean -> bean.getDangerManager().split("_")[0]).collect(Collectors.toSet());
                    List<String> noticeCodeList = new ArrayList<>();
                    for (String code : codeLists) {
                        try (SessionFactory sessionFactory = new SessionFactory()) {
                            // 同一个隐患负责人，提交成一条隐患流程
                            List<HiddenDangerDiscovery> discoveryList = dangerDiscoveryList.stream().filter(bean -> code.equals(bean.getDangerManager().split("_")[0])).collect(Collectors.toList());
                            //整理隐患整改记录
                            HiddenDangerMapper mapper = sessionFactory.getMapper(HiddenDangerMapper.class);
                            List<HiddenDangerRectification> rectificationList = new ArrayList<>();
                            List<HiddenDangerRectification> deleteList = new ArrayList<>();
                            List<String> approvalList = new ArrayList<>();
                            for (HiddenDangerDiscovery dangerDiscovery : discoveryList) {
                                //查询提交的隐患是不是已经有了整改记录；
                                List<HiddenDangerRectification> rectificationList1 = sessionFactory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                                //删除之前有的整改记录信息
                                if (rectificationList1 != null && rectificationList1.size() > 0) {
                                    deleteList.addAll(rectificationList1);
                                }
                                //保存隐患整改信息，主要是配置隐患整改信息的验证人
                                HiddenDangerRectification rectification = new HiddenDangerRectification();
                                //保存整改信息
                                rectification.setHiddenDangerId(dangerDiscovery.getId());
                                rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                                rectification.setAddTime(dangerDiscovery.getUpdateTime());
                                rectification.setAddUser(user.getName());
                                rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                                rectification.setUpdateUser(user.getName());
                                rectification.setRectifier(dangerDiscovery.getDangerManager());
                                rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                                rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                                rectification.setSolution(dangerDiscovery.getDescription());
                                List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
                                List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(dangerDiscovery.getDangerManager().split("_")[0]).getData();
                                if (!approvalList.contains(staffBeanList.get(0).getUserid())) {
                                    approvalList.add(staffBeanList.get(0).getUserid());
                                }
                                rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
                                rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                                rectification.setDelayState(0);
                                rectification.setRectificationState(items == null ? null : items.getId());
                                rectificationList.add(rectification);
                            }
                            //更新选中的隐患为确认状态；启动隐患流程
                            List<String> ids = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                            mapper.updateDangerState(2, ids);
                            try{
                                for (HiddenDangerDiscovery discovery : discoveryList) {
                                    List<Message> messages = new ArrayList<>();
                                    if(discovery.getCopyPerson() != null) {
                                        String[] copyPersons = discovery.getCopyPerson().split(",");
                                        for(String copyPerson : copyPersons) {
                                            Message message = new Message();
                                            message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                            message.setTitle("有一项您关注的隐患整改");
                                            message.setIsRead(0);
                                            message.setIsRemove(0);
                                            message.setAddTime(new Date());
                                            message.setAddUser(discovery.getAddUser());
                                            message.setContent("隐患描述：" + discovery.getDescription());
                                            message.setReceiverCode(copyPerson.split("_")[0]);
                                            messages.add(message);
                                        }
                                    }
                                    if(messages != null && messages.size()> 0) {
                                        factory.getMapper(MessageMapper.class).batchInsert(messages);
                                    }
                                }
                            }catch (Exception e){
                                logger.error(e.getMessage(),e);
                            }
                            mapper.batchInsertRectification(rectificationList);
                            if (deleteList != null && deleteList.size() > 0) {
                                List<String> deleteIdList = deleteList.stream().map(HiddenDangerRectification::getId).collect(Collectors.toList());
                                mapper.bateDeleteRectification(deleteIdList);
                            }
                            Date date = new Date();
                            Audit auditBean = new Audit();
                            auditBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                            auditBean.setUpdateUser(user.getName());
                            auditBean.setUpdateTime(date);
                            auditBean.setAddTime(date);
                            auditBean.setAddUser(user.getName());
                            auditBean.setFlowType(2);
                            auditBean.setOperation(1);
                            auditBean.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
                            auditBean.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
                            auditBean.setNowNodeCode("Process-task2");
                            auditBean.setTitle("隐患整改流程");
                            auditBean.setCorpCode(discoveryList.get(0).getCorpCode());
                            auditBean.setBusinessIds(new Gson().toJson(ids));
                            auditBean.setInitiatorCode(user.getCode());
                            auditBean.setTemplateKey(hiddenDangerWorkFlow);
                            auditBean.setInitiatorAccount(user.getUserid());
                            auditBean.setSetCode(riskDangerSetCode);
                            auditBean.setDescription("隐患整改流程");
                            auditBean.setState(1);
                            Map<String, Object> businessDataMap = new HashMap<>();
                            String userid = approvalList.stream().collect(Collectors.joining(","));
                            businessDataMap.put("rectifier", userid);
                            businessDataMap.put("reviewer", userid);
                            businessDataMap.put("verification", user.getUserid());
                            if (!flowManagement.initFlow(user, auditBean, businessDataMap)) {
                                // 如果自动提交隐患失败，将隐患修改为草稿，可在隐患台账处提交
                                factory.getMapper(HiddenDangerMapper.class).updateDangerState(0, ids);
                                sessionFactory.close(false);
                            } else {
                                // 提交成功，生成整改通知书
                                String noticeCode = HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(sessionFactory, user, discoveryList);
                                if (StringUtils.isNotEmpty(noticeCode)) {
                                    noticeCodeList.add(noticeCode);
                                }
                                sessionFactory.close();
                            }
                        }
                    }
                }
                // 修改隐患为草稿状态
//                if (null != dangers && dangers.size() > 0) {
//                    for (HiddenDangerDiscovery dangerDiscovery : dangers) {
//                        dangerDiscovery.setState(0);
//                    }
//                    factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangers);
//                }
                factory.close();
            }
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            MaterialCheckRecord entity = queryOne(audit.getBusinessIds()).getData();
            if (null != entity) {
                entity.setStatus(1);
                factory.getMapper(MaterialCheckRecordMapper.class).update(entity);
                factory.close();
            }
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(MaterialCheckRecordServiceImpl.class.getName(), this);
        // map.put(HiddenDangerDiscoveryServiceImpl.class.getName(), new HiddenDangerDiscoveryServiceImpl());
    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
